'use strict';

angular.module('app.controllers', [])

.controller('WelcomeCtrl', ['$scope', function($scope){

}])

.controller('ListCtrl', ['$scope','$rootScope','Lists','$stateParams','$ionicListDelegate','$timeout',function($scope,$rootScope,Lists,$stateParams,$ionicListDelegate,$timeout){

    $scope.lists = Lists.list($stateParams.page);

    $scope.data = {
        showDelete: false
    };

    // 下拉更新
    $scope.doRefresh = function(){
        $timeout( function() {
            $scope.lists = Lists.list($stateParams.page);
            //Stop the ion-refresher from spinning
            $scope.$broadcast('scroll.refreshComplete');
        }, 1000);
    }

    // 移动
    $scope.moveItem = function(item, fromIndex, toIndex) {
        $scope.items.splice(fromIndex, 1);
        $scope.items.splice(toIndex, 0, item);
        // todo: 排序
    };

    // 删除
    $scope.onDelete = function(item) {
        $scope.rstatus = Lists.del(item.id);
        $scope.rstatus.$promise.then(function(r){
            if (r.status) {
                $scope.lists.list.splice($scope.lists.list.indexOf(item), 1);
                // $scope.lists = Lists.list($routeParams.page);
            };
        }); 
    };

    $scope.showDeleteButtons = function() {
        $ionicListDelegate.showDelete(true);
    };
    
}])

.controller('ListCreateCtrl', ['$scope','$rootScope','Lists', function($scope,$rootScope,Lists){
    $scope.data = {title:"",content:'',cid:27};

    $scope.save = function(){
       $scope.rstatus = Lists.create($scope.data);
    }

}])

.controller('ListEditCtrl', ['$scope','$rootScope','Lists','$stateParams', function($scope,$rootScope,Lists,$stateParams){
    $scope.data = {title:"",content:'',id:'',cid:''}
    
    Lists.one($stateParams.listId).$promise.then(function (r) {
     $scope.data.title = r.title;
     $scope.data.content = r.content;
     $scope.data.id = r.id;
     $scope.data.cid = r.cid;
    });

    $scope.save = function(){
       $scope.rstatus =Lists.save($scope.data);
    }

}])


;